/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2013 www.pretty-tools.com
 */

g_wsshImageResolver.onRulesUpdated = function () {
    this.logger.debug("onRulesUpdated: reload rules");
    this.loadRules();
}

g_wsshImageResolver.loadRules = function () {
    this.logger.debug("loadRules: loading items from background page");

    var resolver = this;

    this._items = null;
    numberOfImages = null;

    chrome.runtime.sendMessage({call: "g_wsshImageResolver.getItems"}, function(response) {
        resolver.initializeItems(response.returnedValue);

        if (resolver.logger.enabled) resolver.logger.debug("loadRules: loaded items: " + resolver._items.length);

        if (!initialized)
            initialize();
    });
}

g_wsshImageResolver.initializeItems = function (items) {
    var domains = [];
    for (var i in items)
    {
        var item = items[i];
        var pages = item.pages;

        var domain = new wsshWebDomainProfile();
        for (var d in item) // copy properties
            domain[d] = item[d];

        domain.pages = [];
        for (var j in pages)
        {
            var page = new wsshWebPageProfile();

            for (var p in pages[j]) // copy properties
                page[p] = pages[j][p];

            if (!!page.patternAsString)
                page.pattern = new RegExp(page.patternAsString, "i");
            if (!!page.elementPatternAsString)
                page.elementPattern = new RegExp(page.elementPatternAsString, "i");

            domain.pages.push(page)
        }

        domains.push(domain);
    }
    this._items = domains;
}

g_wsshImageResolver.init();
